import { __bl } from '@/arms';
import store from '@/store';
import type { TAxiosExtConfig } from '@bud-fe/request/es/axios';
import AxiosRequest from '@bud-fe/request/es/axios';
import { authHelper } from '@bud-fe/utils';
import { message } from 'antd';
import type { AxiosRequestConfig } from 'axios';
import { config } from 'ice';
import { debounce } from 'lodash-es';

/**
 * TODO: authHelper 配置。如果需要需要修改默认配置，放开以下注释，否则删除。
 */
// authHelper.config({
//   /** 本地存储模式。默认 cookies */
//   storageMode: 'localStorage',
//   /**
//    * 是否开启sso（ab-inbev.cn 域下共享 token）。默认 false
//    * NOTE: 仅当 storageMode为'cookies' 有效
//    * */
//   sso: true,
// });

const redirectToLogin = debounce((msg: string) => {
  message.error(msg);
  store
    .getModelDispatchers('user')
    .logout()
    .then(() => {
      setTimeout(() => {
        window.location.href = `${window.location.origin}/login`;
      }, 1000);
    });
}, 100);

// axios 配置
const requestConfig: AxiosRequestConfig = {
  baseURL: config.baseURL,
};

// 额外配置
const extConfig: TAxiosExtConfig = {
  // 可选，设置重复请求策略，值为：disabled | useCurrent | usePrevious，默认为 usePrevious
  // disabled: 不对重复请求做额外处理； useCurrent： 取消上一次未结束的而使用当前触发的；usePrevious： 取消当下触发的而使用上次未结束的
  // 如果某些接口需要改变 repeatMode, 也可以在具体的接口方法里传参重置
  repeatMode: 'useCurrent',
  responseAction: {
    default: (msg) => {
      message.error(msg);
    },
    repeat: (msg) => {
      message.error(msg);
    },
    complete: (detailInfo) => {
      if (config.env !== 'local') {
        const { request, response, success, duration } = detailInfo;
        __bl.api({
          api: request.url,
          success,
          time: duration,
          code: response.data?.code,
          // NOTE: ARMS的msg字段有字数上限，故以“-”拼接入参和出参，尽量减少字数占用
          msg: `${JSON.stringify(request?.params || {})}-${JSON.stringify(response?.data || {})}`,
        });
      }
    },
    401: (msg) => {
      redirectToLogin(msg);
    },
  },
  authHelper,
};

const request = new AxiosRequest(requestConfig, extConfig);

export default request;
